package com.action;

import cn.hutool.core.io.FileUtil;
import com.annotation.Lock;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.config.CopyFile;
import com.excel.ExcelUtil;
import com.pojo.Dictionary;
import com.pojo.*;
import com.service.*;
import com.util.*;
import com.vo.StaffVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: T-bao
 * @Date: 2021-3-27 17:46
 * @Description:
 */
@RestController
@RequestMapping("/staff")
public class StaffAction extends CopyFile {

    private static DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

    @Autowired
    private StaffService staffService;

    @Autowired
    private QiyeService qiyeService;

    @Autowired
    private WuyeService wuyeService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private StaffHistoryService staffHistoryService;
//    @Autowired
//    private AdminRoleService adminRoleService;

    @Autowired
    private AlertService alertService;

    @Value("${upload.dir}")
    private String upload;

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${server.url}")
    private String host;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private SshCopyFileService sshCopyFileService;

//    @Autowired
//    private StaffQiyeChangeRecordService staffQiyeChangeRecordService;

    /**
     * 员工绑定卡号
     * @return
     */
    @RequestMapping("/staffBangka")
    public ResponseBean staffBangka(String id,String cardNo){
        long count = staffService.count(new QueryWrapper<Staff>().eq("card_no",cardNo));
        long staffCount = staffService.count(new QueryWrapper<Staff>().eq("card_no",cardNo).eq("id",id));
        if (count > staffCount){
            return ResponseBean.error("该卡号已被绑定");
        }
        Staff sta = staffService.selectID(id);
        if (sta != null){
            sta.setCardNo(cardNo);
            if (staffService.updateById(sta)){
                return ResponseBean.ok("绑定成功");
            }
        }
        return ResponseBean.error("绑定失败");
    }


    /**
     * 判断证件号是否已存在
     *
     * @param sfz 证件号
     * @return
     */
    @RequestMapping("/sfzShifouExist")
    @ResponseBody
    public ResponseBean sfzShifouExist(String sfz) {
//        System.out.println("证件号："+sfz);
        int x = staffService.sfzCount(sfz);
        return new ResponseBean(0, x, "", "");
    }

    /**
     * 查找未审核员工
     */
    @RequestMapping("/shenhestaff")
    public ResponseBean shenhestaff(String name, int page, int limit) {
        if (name == "") {
            name = null;
        }
        if (page == 1) {
            page = 0;
        } else {
            page = (page * limit) - limit;
        }
        int count = staffService.shenhecount(name);
        return new ResponseBean(0, count, "成功", staffService.shenheStaff(name, page, limit));
    }

    /**
     * 查询需要审核公司和员工数目
     */
    @RequestMapping("/daishenhe")
    public ResponseBean daishenhe() {
//        ThreadContext.bind(manager);
//        Subject subject = SecurityUtils.getSubject();
//        try{
//            subject.checkPermission("/qiye/updateshqiye");
//        }catch(AuthorizationException e){
//            return ResponseBean.error("没有权限");
//        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("gongsi", qiyeService.shenhecount(null));
        map.put("staff", staffService.shenhecount(null));
        return new ResponseBean(200, 1, "查找成功", map);
    }

    /**
     * 查询已到期，快到期员工人数
     */
    @RequestMapping("/daijiaofei")
    public ResponseBean daijiaofei() {
//        ThreadContext.bind(manager);
//        Subject subject = SecurityUtils.getSubject();
//        try{
//            subject.checkPermission("/shoufei/addshoufei");
//        }catch(AuthorizationException e){
//            return ResponseBean.error("没有权限");
//        }
        Date time = new Date();
        Date cstime = addDate(15);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("yidaoqi", staffService.ydqcount(null, time));
        map.put("kuaidaoqi", staffService.kdqcount(null, time, cstime));
//        map.put("gongsi",qiyeService.shenhecount(null));
//        map.put("staff",staffService.shenhecount(null));
        return new ResponseBean(200, 1, "查找成功", map);
    }

    /**
     * 查找已到期员工
     *
     * @param name  员工姓名
     * @param page  页数
     * @param limit 条数
     * @return
     */
    @RequestMapping("/yidaoqistaff")
    public ResponseBean yidaoqistaff(String name, int page, int limit) {

        if (name == "") {
            name = null;
        }
        if (page == 1) {
            page = 0;
        } else {
            page = (page * limit) - limit;
        }
        Date time = new Date();
        int count = staffService.ydqcount(name, time);
        return new ResponseBean(0, count, "成功", staffService.yidaoqiStaff(name, page, limit, time));
    }

    /**
     * 查找快到期员工
     *
     * @param name  员工姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/kuaidaoqistaff")
    public ResponseBean kuaidaoqistaff(String name, int page, int limit) {

        if (name == "") {
            name = null;
        }
        if (page == 1) {
            page = 0;
        } else {
            page = (page * limit) - limit;
        }
        Date time = new Date();
        Date cstime = addDate(15);
        //System.out.println("15天后时间："+cstime);
        int count = staffService.kdqcount(name, time, cstime);
        return new ResponseBean(0, count, "成功", staffService.kuaidaoqiStaff(name, page, limit, time, cstime));
    }

    /**
     * 返回多少天后的时间
     *
     * @param num
     * @return
     */
    //num为需要增加的天数
    public static Date addDate(int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, num);
        Date date = calendar.getTime();
        return date;
    }


    /**
     * 查询所有员工
     */
//    @RequestMapping("/selectallstaff")
//    @Deprecated
//    public ResponseBean selectallstaff(){
//        List<Staff> list = staffService.list();
//        return new ResponseBean(0,1,"遍历员工成功",list);
//    }

    /**
     * @param staff
     * @return 修改员工
     */
    @RequestMapping("/updatestaff")
    @Lock(name = "batchAddStaff")
    public ResponseBean updateQiye(@RequestBody Staff staff, HttpServletRequest request) throws ParseException {
        if (StringUtil.isNull(staff.getPicture())) {
            staff.setPicture(null);
        }
        Staff sta = staffService.selectID(staff.getId());
//        String name = staff.getName();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String dateString = staff.getCstime();

        Date date = format.parse(dateString);
        if (sta.getCstime().startsWith("00")) {
            if (!sta.getCstime().equals(staff.getCstime())) {

                Pattern pattern1 = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");
                Matcher mt1 = pattern1.matcher(staff.getName());
                if (mt1.matches()) {
                    return new ResponseBean(1, 1, "姓名不能是纯数字！", "姓名不能是纯数字");
                }

                String str[] = dateString.split("/");
                String monthStr = "";
                String dayStr = "";
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                // 获取出生年月，没有2位数则自动补0
                if (str[1].startsWith("0")) {
                    monthStr = str[1];
                } else {
                    monthStr = month >= 10 ? String.valueOf(month) : "0" + month;
                }
                if (str[2].startsWith("0")) {
                    dayStr = str[2];
                } else {
                    dayStr = day >= 10 ? String.valueOf(day) : "0" + day;
                }
                // 去数字
                String strNum = staff.getName().replaceAll("\\d+", "");
                // 去空格
                String strName1 = StringUtils.deleteWhitespace(strNum);
                String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，·、？]";
                Pattern pt = Pattern.compile(regEx);
                Matcher mc = pt.matcher(strName1);
                // 去掉名字中的特殊字符
                String newName = mc.replaceAll("").trim();
                String tmpName = newName;

                Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
                Matcher m = p.matcher(newName);
                String one = "";
                // 判断是否有中文
                if (m.find()) {
                    Pattern pattern = Pattern.compile("[^\u4E00-\u9FA5]");
                    Matcher matcher = pattern.matcher(newName);
                    // 获取所有中文
                    newName = matcher.replaceAll("");
                    newName = StringUtils.deleteWhitespace(newName);
                    // 中文个数
                    if (newName.length() > 1) {
                        // 截最后2位生成拼音首字母
                        newName = newName.substring(newName.length() - 2);
                        //newName = ChineseToEnglishUtil.getPinYinHeadChar(newName);
                        newName = PinYinJPUtil.changeToGetShortPinYin(newName);
                    } else if (newName.length() == 1) {
                        // 取一个汉字拼音的前2位
                        //newName = ChineseToEnglishUtil.getPingYin(newName);
                        newName = PinYinJPUtil.changeToTonePinYin(newName);
                        if (newName.length() == 1 && tmpName.length() > 1) {
                            Matcher m2 = p.matcher(tmpName);
                            if (m2.find()) {
                                Pattern pattern2 = Pattern.compile("[^\u4E00-\u9FA5]");
                                Matcher matcher2 = pattern2.matcher(tmpName);
                                // 获取所有中文
                                String tmpName1 = matcher2.replaceAll("");
                                String tmpName2 = StringUtils.deleteWhitespace(tmpName1);
                                // 获取中文之后的字符串
                                String str3 = tmpName.substring(0, tmpName.indexOf(tmpName2));
                                String str4 = tmpName.substring(str3.length() + 1, tmpName.length());
                                Pattern pt2 = Pattern.compile(regEx);
                                Matcher mc2 = pt2.matcher(str3);
                                // 去掉中文前面特殊字符
                                String str6 = mc2.replaceAll("").trim();

                                Pattern pt3 = Pattern.compile(regEx);
                                Matcher mc3 = pt3.matcher(str4);
                                // 去掉中文前面特殊字符
                                String str7 = mc3.replaceAll("").trim();
                                //判断前面是否有两个字符
                                if (str6.length() >= 2) {
                                    newName = str6.substring(0, 2);
                                } else {
                                    if (str7.length() > 1) {
                                        newName = newName + str7.substring(0, 1);  // lgh ------------------------
                                    } else if (str7.length() == 1) {
                                        newName = newName + str7;
                                    } else {
                                        return new ResponseBean(1, 1, "姓名不符合规范", "姓名不符合规范");
                                    }
                                }
                            }
                        } else if (newName.length() == 1) {// 处理"啊"，"哦"，"额"单音
                            newName = newName + newName;
                        } else {
                            if (newName != null && newName.length() > 2) {
                                newName = newName.substring(0, 2);
                            }
                        }
                    }
                    // 中文名字转拼音首字母大写
                    one = newName.toUpperCase();
                } else if (Pattern.compile("[a-zA-Z]").matcher(newName).find()) {
                    newName = newName.replaceAll("[^a-zA-Z]", "");
                    if (newName.length() > 1) {
                        newName = newName.substring(0, 2);
                    } else if (newName.length() == 1) {
                        newName = newName + newName;
                    } else {
                        return new ResponseBean(1, 1, "姓名不能为空", "姓名不能为空");
                    }
                    one = newName.toUpperCase();
                } else if (Pattern.compile("[\u1000-\u109F]").matcher(newName).find()) {
                    one = "MD";
                } else if (Pattern.compile("[\u0E80-\u0EFF]").matcher(newName).find()) {
                    one = "LW";
                } else if (Pattern.compile("[\u0E00-\u0E7F]").matcher(newName).find()) {
                    one = "TG";
                }
                Qiye qiye = qiyeService.selectID(sta.getQiye().getId());
                Wuye wuye = wuyeService.selectID(qiye.getWyID());
                // 获取物业编码最后两位
                String tmpCode = String.valueOf(wuye.getWycode());
                if (tmpCode.length() < 2) {
                    return new ResponseBean(1, 1, "物业编码少于2位，无法生成员工编号", "物业编码少于2位，无法生成员工编号");
                }
                String two = tmpCode.substring(tmpCode.length() - 2);
                Dictionary dictionary = dictionaryService.getDicByName("Zy", staff.getZhiye());
                String tree = dictionary.getCode();
                String four = monthStr + dayStr;
                String monthStr2 = "";
                if (monthStr.equals("10")) {
                    monthStr2 = "0" + monthStr;
                } else {
                    monthStr2 = monthStr;
                }
                String dayStr2 = "";
                if (dayStr.equals("10")) {
                    dayStr2 = "0" + dayStr;
                } else {
                    dayStr2 = dayStr;
                }
                String four2 = monthStr2 + dayStr2;
                int five = 1;
                int six = 0;
                if (staff.getSex() == 1) {
                    for (int j = 0; j < 10; j++) {
                        if (j % 2 == 0) {
                            continue;
                        }
                        six = j;
                        break;
                    }
                } else {
                    for (int j = 0; j < 10; j++) {
                        if (j % 2 == 0) {
                            six = j;
                            break;
                        }
                        continue;
                    }
                }
                String bh = one + two + tree + four + five + six;
                String bh2 = one + two + four2;
                String bh3 = generateBh(bh, staff.getSex());
                staff.setBh(bh3);
                staff.setBh2(bh2);
            }
        }

//        if (!staff.getZhiye().equals(sta.getZhiye())) {
//            ZhiyeChange zhiyeChange2 = zhiyeChangeService.getZhiyeChangeStatusByStaff(staff.getId());
//            if (zhiyeChange2 != null) {
//                return new ResponseBean(1, 1, "员工职业正在审核中", "员工职业正在审核中");
//            }
//        }

//        BusinessOccupation businessOccupation = (BusinessOccupation) request.getSession().getAttribute("businessOccupation");
//        GroupOffice groupOffice = (GroupOffice) request.getSession().getAttribute("groupOffice");
        String role = null;
//        if (null != businessOccupation) { // 工商
            role = "gs";
//        } else if (null != groupOffice) { //集团办公室
//            role = "jt";
//        }

        Dictionary dictionary = dictionaryService.getDicByName("Zy", sta.getZhiye());
        Dictionary dictionary2 = dictionaryService.getDicByName("Zy", staff.getZhiye());

        // role为空表示集团后台修改走原来处理逻辑，不为空则是工商或集团办公室登录
        // 职业被修改
        // 职业不属于同一机构
//        if (ValidateHelper.isNotEmptyString(role) && !staff.getZhiye().equals(sta.getZhiye())
//                && !dictionary.getValue().equals(dictionary2.getValue())) {

//            ZhiyeChange zhiyeChange = new ZhiyeChange();
//            zhiyeChange.setStaffId(staff.getId());
//            zhiyeChange.setOldZhiye(sta.getZhiye());
//
//            zhiyeChange.setOldZhiyeGs(dictionary.getValue());
//            zhiyeChange.setNewZhiye(staff.getZhiye());
//
//            zhiyeChange.setNewZhiyeGs(dictionary2.getValue());
//            zhiyeChange.setCreateTime(new Date());
//            zhiyeChange.setStatus(0);
//            if (zhiyeChangeService.save(zhiyeChange)) {
//                return new ResponseBean(0, 1, "提交成功，请等待审核", "提交成功，请等待审核");
//            } else {
//                return new ResponseBean(1, 1, "提交失败", "提交失败");
//            }
//        } else {
            // 将其他没有修改的数据也从数据库同步
            /*staff.setWhiteList(sta.getWhiteList());
            staff.setWhite_time(sta.getWhite_time());
            staff.setJcFlag(sta.getJcFlag());
            staff.setJcResult(sta.getJcResult());
            staff.setJcTime(sta.getJcTime());
            staff.setLast_out_time(sta.getLast_out_time());
            staff.setIsZsFlag(sta.getIsZsFlag());
            staff.setIsAppStatus(sta.getIsAppStatus());
            staff.setZkFlag(sta.getZkFlag());
            staff.setCardBalance(sta.getCardBalance());
            staff.setZkFlag(sta.getZkFlag());
            staff.setZkTime(sta.getZkTime());
            staff.setExpDay(sta.getExpDay());
            staff.setQrCodeExpDay(sta.getQrCodeExpDay());
            staff.setGmInfo(sta.getGmInfo());*/
            if (staffService.updateById(staff)) {
                // 判断员工企业是否有变更
                if (StringUtil.isNotNull(staff.getQyID()) && !staff.getQyID().equals(sta.getQyID())) {
//                    staffQiyeChangeRecordService.saveStaffQyChangeRecord(sta.getQyID(), staff.getQyID(), staff.getId());
                }
                if (StringUtil.isNotNull(staff.getPicture()) && staff.getPicture().equals(sta.getPicture()) == false) {
                    FileUtil.copy(tmp + staff.getPicture(), upload, true);
                    sshCopyFileService.copy(upload + staff.getPicture());
                    sshCopyFileService.copyToWjy(upload + staff.getPicture());
                    List<Alert> alertList = alertService.getAlertByStaff(staff.getId());
                    if (ValidateHelper.isNotEmptyCollection(alertList)) {
                        for (Alert alert : alertList) {
                            alertService.removeById(alert.getId());
                        }
                    }
                }
                return new ResponseBean(0, 1, "修改成功", "修改成功");
            } else {
                return new ResponseBean(1, 1, "修改失败", "修改失败");
            }
//        }

    }

    /**
     * 员工开卡
     *
     * @param staff
     * @return
     */
    @RequestMapping("/staffkk")
    public ResponseBean staffkk(@RequestBody Staff staff) {

        Staff staff1 = staffService.selectID(staff.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd");
        String date = sdf.format(staff1.getCstime());
        if (date.startsWith("0")) {
            return new ResponseBean(2, 1, "开卡失败", "员工出生日期无效，不能开卡");
        }
        if (staffService.updateById(staff)) {
            return new ResponseBean(0, 1, "开卡成功", "开卡成功");
        }
        return new ResponseBean(1, 1, "开卡失败", "开卡失败");
    }

    /**
     * 集团新增员工
     *
     * @param staff 员工类
     * @return
     */
    @RequestMapping("/addstaff")
    public ResponseBean jtAddStaff(@RequestBody Staff staff, HttpServletRequest request) throws ParseException {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
//        List<String> list = adminRoleService.shifouGuanliyuan(userinfo.getId());
//        for (int X = 0; X < list.size(); X++) {
//            //管理员新增
//            if (list.get(X) == "管理员" || list.get(X).equals("管理员")) {
//                staff.setShstatus(1);
//                return addStaff(staff);
//            }
//        }
//        //录入员新增
//        staff.setShstatus(0);
        staff.setShstatus(1);
        if (null != admin) {
            staff.setOperUser(admin.getId());
        }
        ResponseBean bean = addStaff(staff);
        return bean;
    }


    /**
     * 物业新增员工
     *
     * @param staff 员工类
     * @return
     */
    @RequestMapping("/wy_addstaff")
    @Lock(name = "batchAddStaff")
    public ResponseBean wyAddStaff(@RequestBody Staff staff, HttpServletRequest request) throws ParseException {
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
        staff.setShstatus(0);
        if (null != wuye) {
            staff.setOperUser(wuye.getId());
        }
        ResponseBean bean = addStaff(staff);
        return bean;
    }

    /**
     * 查询物业包含员工
     *
     * @return
     */
    @RequestMapping("/staff_list_by_wy")
    public ResponseBean staffListByWy(HttpServletRequest request, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
        IPage<Staff> res = staffService.staffListByWy(wuye.getId(), page, limit);
        return new ResponseBean(0, res.getTotal(), "ok", res.getRecords());
    }

    private ResponseBean addStaff(Staff staff) throws ParseException {
        //        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//        staff.setCreatetime(df.format(new Date()));
//        staff.setDqtime(df.format(new Date()));
        Pattern pattern1 = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");
        Matcher mt1 = pattern1.matcher(staff.getName());
        if (mt1.matches()) {
            return new ResponseBean(1, 1, "姓名不能是纯数字！", "姓名不能是纯数字");
        }
        if (ValidateHelper.isNotEmptyString(staff.getSfz())) {
            StaffHistory staffHistory = staffHistoryService.getStaffHistoryBySfz(staff.getSfz());
            if (null != staffHistory) {
                return new ResponseBean(1, 1, "该员工在员工回收站中！", "该员工在员工回收站中");
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String dateString = staff.getCstime();
        Date date = format.parse(dateString);
        String str[] = dateString.split("/");
        String monthStr = "";
        String dayStr = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // 获取出生年月，没有2位数则自动补0
        if (str[1].startsWith("0")) {
            monthStr = str[1];
        } else {
            monthStr = month >= 10 ? String.valueOf(month) : "0" + month;
        }
        if (str[2].startsWith("0")) {
            dayStr = str[2];
        } else {
            dayStr = day >= 10 ? String.valueOf(day) : "0" + day;
        }

        staff.setCstime(staff.getCstime());
        // 去数字
        String strNum = staff.getName().replaceAll("\\d+", "");
        // 去空格
        String strName1 = StringUtils.deleteWhitespace(strNum);
        String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，·、？]";
        Pattern pt = Pattern.compile(regEx);
        Matcher mc = pt.matcher(strName1);
        // 去掉名字中的特殊字符
        String newName = mc.replaceAll("").trim();
        String tmpName = newName;

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
        Matcher m = p.matcher(newName);
        String one = "";
        // 判断是否有中文
        if (m.find()) {
            Pattern pattern = Pattern.compile("[^\u4E00-\u9FA5]");
            Matcher matcher = pattern.matcher(newName);
            // 获取所有中文
            newName = matcher.replaceAll("");
            newName = StringUtils.deleteWhitespace(newName);
            // 中文个数
            if (newName.length() > 1) {
                // 截最后2位生成拼音首字母
                newName = newName.substring(newName.length() - 2);
                //newName = ChineseToEnglishUtil.getPinYinHeadChar(newName);
                newName = PinYinJPUtil.changeToGetShortPinYin(newName);
            } else if (newName.length() == 1) {
                // 取一个汉字拼音的前2位
                //newName = ChineseToEnglishUtil.getPingYin(newName);
                newName = PinYinJPUtil.changeToTonePinYin(newName);
                if (newName.length() == 1 && tmpName.length() > 1) {
                    Matcher m2 = p.matcher(tmpName);
                    if (m2.find()) {
                        Pattern pattern2 = Pattern.compile("[^\u4E00-\u9FA5]");
                        Matcher matcher2 = pattern2.matcher(tmpName);
                        // 获取所有中文
                        String tmpName1 = matcher2.replaceAll("");
                        String tmpName2 = StringUtils.deleteWhitespace(tmpName1);
                        // 获取中文之后的字符串
                        String str3 = tmpName.substring(0, tmpName.indexOf(tmpName2));
                        String str4 = tmpName.substring(str3.length() + 1, tmpName.length());
                        Pattern pt2 = Pattern.compile(regEx);
                        Matcher mc2 = pt2.matcher(str3);
                        // 去掉中文前面特殊字符
                        String str6 = mc2.replaceAll("").trim();

                        Pattern pt3 = Pattern.compile(regEx);
                        Matcher mc3 = pt3.matcher(str4);
                        // 去掉中文前面特殊字符
                        String str7 = mc3.replaceAll("").trim();
                        //判断前面是否有两个字符
                        if (str6.length() >= 2) {
                            newName = str6.substring(0, 2);
                        } else {
                            if (str7.length() > 1) {
                                newName = newName + str7.substring(0, 1);  // lgh ------------------------
                            } else if (str7.length() == 1) {
                                newName = newName + str7;
                            } else {
                                return new ResponseBean(1, 1, "姓名不符合规范", "姓名不符合规范");
                            }
                        }
                    }
                } else if (newName.length() == 1) {// 处理"啊"，"哦"，"额"单音
                    newName = newName + newName;
                } else {
                    if (newName != null && newName.length() > 2) {
                        newName = newName.substring(0, 2);
                    }
                }
            }
            // 中文名字转拼音首字母大写
            one = newName.toUpperCase();
        } else if (Pattern.compile("[a-zA-Z]").matcher(newName).find()) {
            newName = newName.replaceAll("[^a-zA-Z]", "");
            if (newName.length() > 1) {
                newName = newName.substring(0, 2);
            } else if (newName.length() == 1) {
                newName = newName + newName;
            } else {
                return new ResponseBean(1, 1, "姓名不能为空", "姓名不能为空");
            }
            one = newName.toUpperCase();
        } else if (Pattern.compile("[\u1000-\u109F]").matcher(newName).find()) {
            one = "MD";
        } else if (Pattern.compile("[\u0E80-\u0EFF]").matcher(newName).find()) {
            one = "LW";
        } else if (Pattern.compile("[\u0E00-\u0E7F]").matcher(newName).find()) {
            one = "TG";
        }

        Qiye qiye = qiyeService.selectID(staff.getQyID());
        Wuye wuye = wuyeService.selectID(qiye.getWyID());
        // 获取物业编码最后两位
        String tmpCode = String.valueOf(wuye.getWycode());
        if (tmpCode.length() < 2) {
            return new ResponseBean(1, 1, "物业编码少于2位，无法生成员工编号", "物业编码少于2位，无法生成员工编号");
        }
        String two = tmpCode.substring(tmpCode.length() - 2);
        Dictionary dictionary = dictionaryService.getDicByName("Zy", staff.getZhiye());
        String tree = dictionary.getCode();
        String four = monthStr + dayStr;
        String monthStr2 = "";
        if (monthStr.equals("10")) {
            monthStr2 = "0" + monthStr;
        } else {
            monthStr2 = monthStr;
        }
        String dayStr2 = "";
        if (dayStr.equals("10")) {
            dayStr2 = "0" + dayStr;
        } else {
            dayStr2 = dayStr;
        }
        String four2 = monthStr2 + dayStr2;
        int five = 1;
        int six = 0;
        if (staff.getSex() == 1) {
            for (int j = 0; j < 10; j++) {
                if (j % 2 == 0) {
                    continue;
                }
                six = j;
                break;
            }
        } else {
            for (int j = 0; j < 10; j++) {
                if (j % 2 == 0) {
                    six = j;
                    break;
                }
                continue;
            }
        }
        String bh = one + two + tree + four + five + six;
        String bh2 = one + two + four2;
        String bh3 = generateBh(bh, staff.getSex());

        staff.setBh(bh3);
        staff.setBh2(bh2);

        staff.setDqtime(new Date());
        staff.setCreatetime(new Date());

        String name = staff.getName();
//        int i = staffService.countName(name);
//        if (i == 0) {
        staff.setJfstatus(2);
        staff.setStatus(1);
        if (staffService.save(staff)) {
            if (StringUtil.isNotNull(staff.getPicture())) {
                FileUtil.copy(tmp + staff.getPicture(), upload, true);
                sshCopyFileService.copy(upload + staff.getPicture());
                sshCopyFileService.copyToWjy(upload + staff.getPicture());
                //tmp复制图片到upload
//                    String srcPathStr = tmp+staff.getPicture(); //源文件地址
//                    String desPathStr = upload; //目标文件地址
//                    copy(srcPathStr, desPathStr);
            }
            return new ResponseBean(0, 1, "成功", "新增成功");
        } else {
            return new ResponseBean(1, 1, "失败", "新增失败");
        }
//        } else {
//            return new ResponseBean(2, 1, "该姓名已存在", "该姓名已存在");
//        }
    }


    /**
     * 查询员工（已审核）
     *
     * @param name  姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/selectstaff")
    public ResponseBean selectStaff(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                    @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye,
                                    @RequestParam(required = false) String zhiye, @RequestParam(required = false) String guoji, String name1,
                                    HttpServletRequest request) {
//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        String queryStr = null;
//            queryStr = "gs";
        if (name == null) {
            name = name1;
        }
        if (ValidateHelper.isEmptyString(name)) {
            name = null;
        }
        if (ValidateHelper.isEmptyString(wuye)) {
            wuye = null;
        }
        if (ValidateHelper.isEmptyString(qiye)) {
            qiye = null;
        }
        if (ValidateHelper.isEmptyString(zhiye) || zhiye.equals("选择职业")) {
            zhiye = null;
        }
        if (ValidateHelper.isEmptyString(guoji) || guoji.equals("选择国籍")) {
            guoji = null;
        }
        IPage<StaffVO> iPage = staffService.selectStaff(name, page, limit, wuye, qiye, zhiye, guoji, queryStr);
        List<StaffVO> records = iPage.getRecords();
//        for(StaffVO staffVO : records) {
//            if(staffService.isThb(staffVO.getZhiye())) {
//                staffVO.setSfz(null);
//                staffVO.setPicture(null);
//            }
//        }
        return new ResponseBean(0, iPage.getTotal(), "成功", records);
    }


    /**
     * 制作工牌时查询员工信息(在职已审核)
     *
     * @param name  姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/selectstaffGp")
    public ResponseBean selectstaffGp(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                      @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye, @RequestParam(required = false) String zkFlag,
                                      @RequestParam(required = false) String zhiye, @RequestParam(required = false) String dataFlag, HttpServletRequest request) {

        String queryStr = null;
            queryStr = "gs";

//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        IPage iPage = staffService.selectStaffGP(name, page, limit, wuye, qiye, zkFlag, zhiye, dataFlag, queryStr);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 挂失补卡员工列表
     *
     * @param name       姓名
     * @param page       页数
     * @param limit      每页条数
     * @param cardStatus 卡状态
     * @return
     */
    @RequestMapping("/selectstaffGsBk")
    public ResponseBean selectstaffGsBk(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                        @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye, @RequestParam(required = false) String cardStatus,
                                        HttpServletRequest request) {
        String queryStr = null;
//            queryStr = "gs";
//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        IPage<StaffVO> staffList = staffService.selectStaffByCard(name, page, limit, wuye, qiye, cardStatus, queryStr);
        return new ResponseBean(0, staffList.getTotal(), "成功", staffList.getRecords());
    }

    /**
     * 损坏卡补卡员工列表
     *
     * @param name  姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/selectstaffShBk")
    public ResponseBean selectstaffShBk(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                        @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye) {

//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        System.out.println(name);
        IPage<Staff> staffList = staffService.selectStaffByShbk(name, page, limit, wuye, qiye);
        return new ResponseBean(0, staffList.getTotal(), "成功", staffList.getRecords());
    }

    /**
     * 未开卡员工
     *
     * @param name  姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/selectstaffByWkk")
    public ResponseBean selectstaffByWkk(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                         @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye, @RequestParam(required = false) String zhiye,
                                         HttpServletRequest request) {

        String queryStr = null;
            queryStr = "gs";

//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        IPage iPage = staffService.selectStaffKk(page, limit, name, wuye, qiye, zhiye, queryStr);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }


    /**
     * 删除员工
     *
     * @param id 员工ID
     * @return
     */
    @RequestMapping("/delstaff")
    public ResponseBean delqiye(String id) {
//        System.out.println("删除员工id："+id);
        if (staffService.removeById(id)) {
            return new ResponseBean(0, 1, "成功", "删除成功");
        } else {
            return new ResponseBean(1, 1, "失败", "删除失败");
        }
    }

    /**
     * 修改员工审核状态
     */
    @RequestMapping("/updateshstaff")
    @ResponseBody
    public String updateshstaff(String id) {
        // 修改状态，返回修改后的状态
        Staff gnaddress = staffService.upshStatus(id);
        if (gnaddress != null)
            return gnaddress.getShstatus() + "";
        return "";
    }

    /**
     * 员工离职入职
     */
    @RequestMapping("/stafflizhi")
    @ResponseBody
    public ResponseBean stafflizhi(String id, Integer status) {
        Staff staff = new Staff();
        if (status == 1) {
            staff.setId(id);
            staff.setStatus(0);
            staff.setLztime(new Date());
        } else if (status == 0) {
            staff.setId(id);
            staff.setStatus(1);
            staff.setRztime(new Date());
        }
        return new ResponseBean(0, 1, "修改员工状态", staffService.upStatus(staff));
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @RequestMapping("staff_id")
    @ResponseBody
    public ResponseBean getStaffById(String id) {
        Staff staff = staffService.getById(id);
        if (staff.getCardBalance() == null) {
            staff.setCardBalance(new BigDecimal(0));
            staffService.updateById(staff);
        }
        String res = staffService.checkBh(id);
        if (ValidateHelper.isNotEmptyString(res)) {
            return new ResponseBean(500, "问题数据过滤", "问题数据过滤");
        }
        return new ResponseBean(200, "成功", staffService.getById(id));
    }

    /**
     * 批量导入员工
     *
     * @param file
     * @return
     */
    @PostMapping(value = "batchAddStaff")
    @Lock(name = "batchAddStaff")
    public ResponseBean batchAddStaff(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        String fileName = file.getOriginalFilename();
        Map<String, Object> map = new HashMap<>();
        List<Staff> staffs = new ArrayList<>();
        List<Integer> wycodeList = new ArrayList<>();
        List<String> bhList = new ArrayList<>();
        Map<String, String> resultMap = com.excel.ExcelUtil.importExcel(fileName, file, staffs, wycodeList, admin);
        if (resultMap.containsKey("error")) {
            return new ResponseBean(500, "失败", resultMap.get("error"));
        }
        if (resultMap.containsKey("sucess")) {
            if (staffService.saveBatch(staffs)) {
                for (Staff staff : staffs) {

                }
                return new ResponseBean(200, "导入成功", staffs);
            }
        }
        return new ResponseBean(500, "失败", "导入失败");
    }

    /**
     * 批量删除员工
     *
     * @param file
     * @return
     */
    @PostMapping(value = "batchDeleteStaff")
    @Lock(name = "batchDeleteStaff")
    public ResponseBean batchDeleteStaff(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        Map<String, Object> resultMap = new HashMap<>();
        List<String> errorList = new ArrayList<>();
        Map<String, String> bhList = new HashMap<>();
        boolean flag = com.excel.ExcelUtil.importDeleteStaff(fileName, file, bhList);
        int i = 0;
        if (flag) {
            if (ValidateHelper.isNotEmptyMap(bhList)) {
                for (Map.Entry<String, String> entry : bhList.entrySet()) {
                    Staff staff = staffService.getStaffByBh(entry.getKey());
                    if (null != staff) {
                        if (staffService.removeById(staff.getId())) {
                            i++;
                            List<StaffHistory> staffHistories = staffHistoryService.getStaffHisByBh(entry.getKey());
                            if (ValidateHelper.isNotEmptyCollection(staffHistories)) {
                                continue;
                            }
                            StaffHistory staffHistory = new StaffHistory();
                            BeanUtils.copyProperties(staff, staffHistory);
                            staffHistory.setCreatetime(new Date());
                            staffHistory.setOperType(0);
                            staffHistory.setRemark(entry.getValue());
                            staffHistoryService.save(staffHistory);
                        }
                    } else {
                        errorList.add("<br>编号：" + entry.getKey() + "，错误信息：" + "<span style='color:red;'>" + entry.getKey() + "，不存在</span>");
                    }
                }
            } else {
                errorList.add("上传文件为空");
            }
        }
        int result = bhList.size() - i;
        if (result < 0) {
            result = 0;
        }
        resultMap.put("success", "总记录数：" + bhList.size() + "，成功数：" + i + "，失败数：" + result);
        resultMap.put("error", errorList);
        return new ResponseBean(200, 1, resultMap);
    }


    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelByStaff")
    public ResponseBean exportExcelByStaff(String staffName, String wuye, String qiye, String zhiye, String guoji, Integer exportType,
                                           HttpServletRequest request, HttpServletResponse response) throws IOException {

        String queryStr = null;
            queryStr = "gs";
        if (StringUtil.isNull(wuye)) {
            wuye = null;
        }
        if (StringUtil.isNull(qiye)) {
            qiye = null;
        }
        if (ValidateHelper.isEmptyString(staffName)) {
            staffName = null;
        }
        if (StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            zhiye = null;
        }
        if (StringUtil.isNull(guoji) || guoji.equals("选择国籍")) {
            guoji = null;
        }
        List<Staff> staffList = staffService.getStaffInfoByExport(staffName, wuye, qiye, zhiye, guoji, queryStr);
        // 判断员工是否是特行办人员，如果是则将照片和证件置空
        for(Staff staff: staffList) {
            if(staffService.isThb(staff.getZhiye())) {
                staff.setPicture(null);
                staff.setSfz(null);
            }
        }
        String cnFileName = new String("员工记录".getBytes(), "utf-8");
        String name = cnFileName + new Date().getTime() + ".xls";
        String fileName = upload + "/excel/" + name;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            if (exportType != null && exportType == 1) {
            String time = String.valueOf(System.currentTimeMillis());
            redisTemplate.boundHashOps("isFineshed").put("status"+time,"0");
            new Thread(){
                @Override
                public void run() {
                try{
                    SXSSFWorkbook workbook = com.excel.ExcelUtil.exportExcelByStaff(fileName, "员工记录", staffList, upload, exportType);
                    OutputStream outputStream = new FileOutputStream(new File(fileName));
                    workbook.write(outputStream);
                    redisTemplate.boundHashOps("isFineshed").put("status"+time,"1");
                    redisTemplate.opsForValue().set("work"+time, "/upload/excel/" + name);
                }catch (Exception e){
                    e.printStackTrace();
                    redisTemplate.boundHashOps("isFineshed").put("status"+time,"2");
                }
                }
            }.start();
                return new ResponseBean(200,"开始导出",time);
            }

            SXSSFWorkbook workbook = com.excel.ExcelUtil.exportExcelByStaff(fileName, "员工记录", staffList, upload, exportType);
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("失败");
        }

        return ResponseBean.ok("成功");

    }

    /**
     * 获取导出任务的结果，从redis中取
     * @param times 时间戳
     * @return
     */
    @PostMapping("/getExportStaffStatus")
    public ResponseBean getExportStaffStatus(String times, HttpServletResponse response) throws IOException {
        if (StringUtil.isNull(times)){
            return new ResponseBean(500,"参数异常",null);
        }
        String result = (String) redisTemplate.boundHashOps("isFineshed").get("status"+times);
        Map map = new HashMap() ;
        map.put("status" , result) ;
        if ("1".equals(result)) {
            String work = (String) redisTemplate.opsForValue().get("work"+times);
            map.put("downloadUrl" , work) ;
        }

        return new ResponseBean(200,"ok",map);
    }

    /**
     * 获取职业
     *
     * @param request
     * @return
     */
    @RequestMapping("/getZyDic")
    public ResponseBean getZyDic(HttpServletRequest request, Integer type) {
//        BusinessOccupation businessOccupation = (BusinessOccupation) request.getSession().getAttribute("businessOccupation");
//        GroupOffice groupOffice = (GroupOffice) request.getSession().getAttribute("groupOffice");
//        if (null != businessOccupation && type == null) {
//            List<Dictionary> zyList = dictionaryService.getDicByZyGs();
//            return new ResponseBean(0, 1, "", zyList);
//        } else if (null != groupOffice && type == null) {
//            List<Dictionary> zyList = dictionaryService.getDicByZyJt();
//            return new ResponseBean(0, 1, "", zyList);
//        } else {
            List<Dictionary> zyList = dictionaryService.getDicByType("Zy");
            return new ResponseBean(0, 1, "", zyList);
//        }
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @RequestMapping("/resetPwd")
    public ResponseBean resetPwd(String id) {
//        Staff staff = staffService.selectID(id);
        Staff staff = staffService.getById(id);
        staff.setPassword(PasswordUtil.jiami("123456"));
        if (staffService.updateById(staff)) {
            return new ResponseBean(200, "密码重置成功", staff);
        }
        return new ResponseBean(500, "密码重置失败", "密码重置失败");
    }

    /**
     * 更新员工制卡状态
     *
     * @param id
     * @return
     */
    @RequestMapping("/updateZyFlag")
    public ResponseBean updateZyFlag(String id, Integer zkFlag, HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        Staff staff = staffService.selectID(id);
        if (zkFlag == 0) {
            staff.setZkFlag(1);
            staff.setIsZsFlag(0);
            staff.setIsAppStatus(0);
            staff.setZkTime(new Date());
            if (null != admin) {
                staff.setZkUser(admin.getId());
            }
        } else {
            staff.setZkFlag(0);
            staff.setIsZsFlag(1);
            staff.setIsAppStatus(1);
            staff.setZkTime(null);
        }

        String bh = StringUtils.deleteWhitespace(staff.getBh());
        staff.setBh(bh);
        if (staffService.updateById(staff)) {
            return new ResponseBean(200, "标识成功", staff);
        }
        return new ResponseBean(500, "标识成失败", "密码重置失败");
    }

    /**
     * 批量更新员工制卡状态
     *
     * @param ids 员工ID集合
     * @return
     */
    @RequestMapping("/batchUpdateZyFlag")
    public ResponseBean batchUpdateZyFlag(String ids, HttpServletRequest request) {
//        System.out.println("员工ID集合："+ids);
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        String[] staffIds = ids.split(",");
        String msg = "";
        for (String id : staffIds) {
            Staff staff = staffService.selectID(id);
            if (staff != null) {
                staff.setZkFlag(1);
                staff.setIsZsFlag(0);
                staff.setIsAppStatus(0);
                staff.setZkTime(new Date());
                if (null != admin) {
                    staff.setZkUser(admin.getId());
                }
                String bh = StringUtils.deleteWhitespace(staff.getBh());
                staff.setBh(bh);
                if (!staffService.updateById(staff)) {
                    if (StringUtil.isNull(msg)) {
                        msg = staff.getName();
                    } else {
                        msg = msg + "," + staff.getName();
                    }
                }
            }
        }
        if (StringUtil.isNull(msg)) {
            return ResponseBean.ok("标识成功");
        }
        return ResponseBean.error(msg + "标识失败");
    }

    /**
     * 删除员工
     *
     * @param id 员工ID
     * @return
     */
    @RequestMapping("/deleteStaff")
    @Lock(name = "batchDeleteStaff")
    public ResponseBean deleteStaff(String id, String remark) {
        Staff staff = staffService.selectID(id);
        StaffHistory staffHistory = new StaffHistory();
        BeanUtils.copyProperties(staff, staffHistory);
        staffHistory.setCreatetime(new Date());
        staffHistory.setOperType(1);
        staffHistory.setRemark(remark);
        StaffHistory hisDb = staffHistoryService.getById(id);
        if (hisDb != null) {
            return ResponseBean.error("删除失败，员工回收站已存在该员工");
        }
        if (staffHistoryService.save(staffHistory)) {
            if (staffService.removeById(id)) {
                return ResponseBean.ok("删除成功");
            }
        }
        return ResponseBean.error("删除失败");
    }

    /**
     * 判断员工与卡号是否匹配
     *
     * @param id
     * @return
     */
    @RequestMapping("/getStaffByCard")
    public ResponseBean getStaffByCard(String cardNo, String id) {
        int result = staffService.getStaffByCard(cardNo, id);
        if (result == 1) {
            return new ResponseBean(500, "员工与卡号不匹配，请联系开发者", "员工与卡号不匹配，请联系开发者");
        } else if (result == 0) {
            return new ResponseBean(500, "白卡", "白卡");
        }
        return new ResponseBean(200, "获取成功", "获取成功");
    }


    /**
     * 导出Excel--制作工牌页面
     */
    @RequestMapping("/exportExcelByGp")
    public ResponseEntity<InputStreamResource> exportExcelByGp(String staffName, String wuye, String qiye, String zkFlag, String zhiye, String dataFlag, HttpServletRequest request) throws IOException {


        String queryStr = null;
            queryStr = "gs";

        if (StringUtil.isNull(wuye)) {
            wuye = null;
        }
        if (StringUtil.isNull(qiye)) {
            qiye = null;
        }
        if (StringUtil.isNull(staffName)) {
            staffName = null;
        }
        if (StringUtil.isNull(dataFlag)) {
            dataFlag = null;
        }
        if (StringUtil.isNull(zkFlag)) {
            zkFlag = null;
        }
        if (StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            zhiye = null;
        }
        String cnFileName = "";
        List<StaffVO> staffList = staffService.exportExcelByGp(staffName, wuye, qiye, zkFlag, zhiye, dataFlag, queryStr);
        if (StringUtil.isNull(zkFlag)) {
            cnFileName = new String("员工记录".getBytes(), "utf-8");
        } else if (zkFlag.equals("0")) {
            cnFileName = new String("未制卡员工记录".getBytes(), "utf-8");
        } else {
            cnFileName = new String("已制卡员工记录".getBytes(), "utf-8");
        }

        String name = cnFileName + new Date().getTime() + ".xls";
        String fileName = upload + "/excel/" + name;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            com.excel.ExcelUtil.exportExcelByGp(fileName, "员工记录", staffList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 校验用户编号
     *
     * @param id
     * @return
     */
    @RequestMapping("check_bh")
    public ResponseBean checkBh(String id) {
        String res = staffService.checkBh(id);
        if (ValidateHelper.isEmptyString(res)) {
            return ResponseBean.OK;
        } else {
            return ResponseBean.error(res);
        }
    }

    /**
     * 批量正面模板用户数据校验-导出
     *
     * @param ids
     * @return
     */
    @RequestMapping("check_batch")
    public ResponseBean check_batch(String[] ids) {
        List<String> errorList = new ArrayList<>();
        if (ids != null) {
            for (String id : ids) {
                staffService.checkBatch(id, errorList);
            }
        }

        if (ValidateHelper.isEmptyCollection(errorList)) {
            return ResponseBean.OK;
        } else {
            return new ResponseBean(500, "失败数据列表", errorList);
        }
    }

    /**
     * 加载时-批量正面模板用户数据校验
     *
     * @param ids
     * @return
     */
    @RequestMapping("check_load")
    public ResponseBean check_load(String[] ids) {
        List<String> errorList = new ArrayList<>();
        if (ids != null) {
            for (String id : ids) {
                staffService.checkLoad(id, errorList);
                ;
            }
        }
        if (ValidateHelper.isEmptyCollection(errorList)) {
            return new ResponseBean(200, "没有异常数据", "没有异常数据");
        } else {
            return new ResponseBean(500, "失败数据列表", errorList);
        }
    }

    /**
     * 解除卡的绑定关系
     *
     * @return
     */
    @RequestMapping("reset_card")
    public ResponseBean resetCard(String id) {
        String res = staffService.resetCard(id);
        return res != null ? ResponseBean.error(res) : ResponseBean.OK;
    }

    /**
     * 绑定卡与用户关系
     *
     * @param uid
     * @param cid
     * @return
     */
    @RequestMapping("bangdin")
    public ResponseBean bangdin(String uid, String cid) {
        String res = staffService.bangdin(uid, cid);
        return res != null ? ResponseBean.error(res) : ResponseBean.OK;
    }

    /**
     * 绑定卡与用户关系
     * @param cid
     * @return
     */
    @RequestMapping("bangdin1")
    public ResponseBean bangdin1(String cid) {
        String res = staffService.bangdin1(cid);
        return res != null ? ResponseBean.error(res) : ResponseBean.OK;
    }

    /**
     * 导出Excel--员工管理页面导出问题数据员工
     */
    @RequestMapping("/exportExcelByProblemData")
    public ResponseEntity<InputStreamResource> exportExcelByProblemData(HttpServletRequest request) throws IOException, ParseException {

        String queryStr = null;
            queryStr = "gs";
        List<StaffVO> staffList = staffService.exportExcelByProblemData(queryStr);
        for(StaffVO staffVO: staffList) {
            if(staffService.isThb(staffVO.getZhiye())) {
                staffVO.setSfz(null);
                staffVO.setPicture(null);
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String cnFileName = new String("问题数据".getBytes(), "utf-8");
        String name = cnFileName + sdf.format(new Date()) + ".xls";
        String fileName = upload + "/excel/" + name;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            com.excel.ExcelUtil.exportExcelByProblemData(fileName, "问题数据", staffList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 员工照片异常处理
     */
    @RequestMapping("/errorPictureCopy")
    public ResponseEntity<InputStreamResource> errorPictureCopy() throws IOException, ParseException {

        List<Staff> staffList = staffService.errorPictureCopy();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String cnFileName = new String("问题数据".getBytes(), "utf-8");
        String name = cnFileName + sdf.format(new Date()) + ".xls";
        String fileName = upload + "/excel/" + name;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            com.excel.ExcelUtil.errorPictureCopy(fileName, "问题数据", staffList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }


    public String generateBh(String bh, Integer sex) {
        String tmpBh = bh.substring(0, bh.length() - 1);
        String str = bh.substring(bh.length() - 1);
        char bh2 = bh.charAt(bh.length() - 1);
        int num = (int) bh2;
        if (num > 47 && num < 58) {
            bh2 = (char) (bh2 - '0');
        }
        int i = 0;
        List<Staff> staffList = staffService.getStaffInfoByBh(bh);
        List<StaffHistory> staffHistoryList = staffHistoryService.getStaffHisByBh(bh);
        if (staffList.size() > 0) {
            if (sex == 1) {
                if (bh2 > 10) {
                    i = bh2 + 1;
                    tmpBh = tmpBh + (char) i;
                } else {
                    i = Integer.valueOf(bh2);
                    i = i + 2;
                    if (i > 10) {
                        i = 'X' + (i - 11) / 2;
                        tmpBh = tmpBh + (char) i;
                    } else {
                        tmpBh = tmpBh + i;
                    }
                }
            } else {
                if (bh2 > 10) {
                    i = bh2 + 1;
                    tmpBh = tmpBh + (char) i;
                } else {
                    i = Integer.valueOf(bh2);
                    i = i + 2;
                    if (i > 10) {
                        i = 'A' + (i - 10) / 2;
                        tmpBh = tmpBh + (char) i;
                    } else {
                        tmpBh = tmpBh + i;
                    }
                }
            }
            return generateBh(tmpBh, sex);
        } else {
            if (staffHistoryList.size() > 0) {
                if (sex == 1) {
                    if (bh2 > 10) {
                        i = bh2 + 1;
                        tmpBh = tmpBh + (char) i;
                    } else {
                        i = Integer.valueOf(bh2);
                        i = i + 2;
                        if (i > 10) {
                            i = 'X' + (i - 11) / 2;
                            tmpBh = tmpBh + (char) i;
                        } else {
                            tmpBh = tmpBh + i;
                        }

                    }
                } else {
                    if (bh2 > 10) {
                        i = bh2 + 1;
                        tmpBh = tmpBh + (char) i;
                    } else {
                        i = Integer.valueOf(bh2);
                        i = i + 2;
                        if (i > 10) {
                            i = 'A' + (i - 10) / 2;
                            tmpBh = tmpBh + (char) i;
                        } else {
                            tmpBh = tmpBh + i;
                        }
                    }
                }
                return generateBh(tmpBh, sex);
            } else {
                return bh;
            }
        }
    }

    /**
     * 获取UUID
     */
    @RequestMapping("/getUUid")
    public ResponseBean getUUid() {
        String random = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("kk" + random, random, 2 * 60, TimeUnit.SECONDS);
        Map result = new HashMap();
        result.put("kk", random);
        return new ResponseBean(1, 1, "生成随机数成功", result);
    }

    /**
     * 查询数据不规范员工信息(在职已审核)
     *
     * @param name  姓名
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/selectStaffGPByProblemData")
    public ResponseBean selectStaffGPByProblemData(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                                   @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye, @RequestParam(required = false) String zkFlag,
                                                   @RequestParam(required = false) String zhiye) {

//        System.out.println("员工姓名："+name+" 页数："+page+" 每页条数："+limit+" 物业："+wuye+" 企业："+qiye);
        IPage iPage = staffService.selectStaffGPByProblemData(name, page, limit, wuye, qiye, zkFlag, zhiye);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }


    /**
     * 获取导出工牌不合格员工
     *
     * @return
     */
    @RequestMapping("/getAlert")
    public ResponseBean getAlert(String id) {
        List<Alert> alertList = alertService.getAlertByStaff(id);
        if (ValidateHelper.isNotEmptyCollection(alertList)) {
            return new ResponseBean(0, "有不合格数据", alertList.get(0).getContent());
        } else {
            return new ResponseBean(1, "没有不合格数据", "没有不合格数据");
        }

    }


    /**
     * 获取员工二维码列表
     *
     * @return
     */
    @RequestMapping("/selectStaffQrCode")
    public ResponseBean selectStaffQrCode(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                          @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye,
                                          @RequestParam(required = false) String zhiye, @RequestParam(required = false) String qrCode) {
        IPage iPage = staffService.selectStaffQrCode(name, page, limit, wuye, qiye, zhiye, qrCode);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 更新员工二维码颜色
     *
     * @param id
     * @return
     */
    @RequestMapping("/updateQrCode")
    public ResponseBean updateQrCode(String id, String qrCode) {
        Staff staff = staffService.selectID(id);
        staff.setQrcode(qrCode);
        if (staffService.updateById(staff)) {
            return new ResponseBean(200, "设置成功", staff);
        }
        return new ResponseBean(500, "设置失败", "设置失败");
    }

    /**
     * 批量更新员工二维码颜色
     *
     * @return
     */
    @RequestMapping("/batchUpdateQrCode")
    public ResponseBean batchUpdateQrCode(String wy, String qy, String zy, String qrCode) {
        if (ValidateHelper.isNotEmptyString(wy)) { //物业不为空
            if (ValidateHelper.isNotEmptyString(qy)) { //企业不为空
                List<Staff> staffList = staffService.getStaffByQyId(qy);
                if (ValidateHelper.isEmptyCollection(staffList)) {
                    return new ResponseBean(500, "该企业下没有员工", "该企业下没有员工");
                }
                if (ValidateHelper.isNotEmptyString(zy)) {  //职业不为空
                    for (Staff staff : staffList) {
                        if (!zy.equals(staff.getZhiye())) {
                            continue;
                        }
                        staff.setQrcode(qrCode);
                        staffService.updateById(staff);
                    }
                } else {  //物业不为空，企业不为空，职业为空
                    for (Staff staff : staffList) {
                        staff.setQrcode(qrCode);
                        staffService.updateById(staff);
                    }
                }
            } else { // 物业不为空，企业为空
                if (ValidateHelper.isNotEmptyString(zy)) { // 物业不为空，企业为空，职业不为空
                    List<Qiye> qiyeList = qiyeService.selectQiyes(wy);
                    if (ValidateHelper.isEmptyCollection(qiyeList)) {
                        return new ResponseBean(500, "该物业下没有企业", "该物业下没有企业");
                    }
                    for (Qiye qiye : qiyeList) {
                        List<Staff> staffList = staffService.getStaffByQyId(qiye.getId());
                        if (ValidateHelper.isNotEmptyCollection(staffList)) {
                            for (Staff staff : staffList) {
                                if (!zy.equals(staff.getZhiye())) {
                                    continue;
                                }
                                staff.setQrcode(qrCode);
                                staffService.updateById(staff);
                            }
                        }
                    }
                } else { // 物业不为空，企业为空，职业为空
                    List<Qiye> qiyeList = qiyeService.selectQiyes(wy);
                    if (ValidateHelper.isEmptyCollection(qiyeList)) {
                        return new ResponseBean(500, "该物业下没有企业", "该物业下没有企业");
                    }
                    for (Qiye qiye : qiyeList) {
                        List<Staff> staffList = staffService.getStaffByQyId(qiye.getId());
                        if (ValidateHelper.isNotEmptyCollection(staffList)) {
                            for (Staff staff : staffList) {
                                staff.setQrcode(qrCode);
                                staffService.updateById(staff);
                            }
                        }
                    }
                }
            }
        } else if (ValidateHelper.isNotEmptyString(qy)) {  //物业为空，企业不为空
            List<Staff> staffList = staffService.getStaffByQyId(qy);
            if (ValidateHelper.isEmptyCollection(staffList)) {
                return new ResponseBean(500, "该企业下没有员工", "该企业下没有员工");
            }
            if (ValidateHelper.isNotEmptyString(zy)) {  //职业不为空
                for (Staff staff : staffList) {
                    if (!zy.equals(staff.getZhiye())) {
                        continue;
                    }
                    staff.setQrcode(qrCode);
                    staffService.updateById(staff);
                }
            } else {  //职业为空
                for (Staff staff : staffList) {
                    staff.setQrcode(qrCode);
                    staffService.updateById(staff);
                }
            }
        } else if (ValidateHelper.isNotEmptyString(zy)) { //物业为空，企业为空 ，职业不为空
            List<Staff> staffList = staffService.getStaffByZhiye(zy);
            if (ValidateHelper.isEmptyCollection(staffList)) {
                return new ResponseBean(500, "该职业下没有员工", "该职业下没有员工");
            }
            for (Staff staff : staffList) {
                staff.setQrcode(qrCode);
                staffService.updateById(staff);
            }
        }

        return new ResponseBean(200, "批量设置成功", "批量设置成功");
    }


    /**
     * 获取员工黑白名单列表
     *
     * @return
     */
    @RequestMapping("/selectStaffWhiteList")
    public ResponseBean selectStaffWhiteList(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,
                                             @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye,
                                             @RequestParam(required = false) String zhiye, @RequestParam(required = false) String whiteList,
                                             @RequestParam(required = false) String qrCode, HttpServletRequest request) {

        String queryStr = null;
            queryStr = "gs";
        IPage iPage = staffService.selectStaffWhiteList(name, page, limit, wuye, qiye, zhiye, whiteList, qrCode, queryStr);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 导出员工黑白名单列表
     *
     * @return
     */
    @RequestMapping("/exportStaffWhiteList")
    public ResponseEntity<InputStreamResource> exportStaffWhiteList(String name, @RequestParam(required = false) String wuye, @RequestParam(required = false) String qiye,
                                                                    @RequestParam(required = false) String zhiye, @RequestParam(required = false) String whiteList,
                                                                    @RequestParam(required = false) String qrCode, HttpServletRequest request) throws IOException {

        String queryStr = null;
            queryStr = "gs";
        List<StaffVO> staffList = staffService.exportStaffWhiteList(name, wuye, qiye, zhiye, whiteList, qrCode, queryStr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String cnFileName = new String("黑白名单".getBytes(), "utf-8");
        String excelName = cnFileName + sdf.format(new Date()) + ".xls";
        String fileName = upload + "/excel/" + excelName;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            com.excel.ExcelUtil.exportStaffWhiteList(fileName, "黑白名单", staffList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(excelName.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 更新员工黑白名单
     *
     * @param id
     * @return
     */
    @RequestMapping("/updateWhiteList")
    public ResponseBean updateWhiteList(String id, Integer whiteList, @RequestParam(required = false) String qrCode, @RequestParam(required = false) Integer expDay) {
        Staff staff = staffService.selectID(id);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", staff.getId());
        updateWrapper.set("white_list", whiteList);
        if (whiteList == 0) {
            updateWrapper.set("qrcode", qrCode);
            updateWrapper.set("qrCodeExpDay", expDay);
            updateWrapper.set("white_time", new Date());
        } else {
            updateWrapper.set("qrcode", "red");
            updateWrapper.set("qrCodeExpDay", null);
        }
        if (staffService.update(updateWrapper)) {
            return new ResponseBean(200, "设置成功", staff);
        }
        return new ResponseBean(500, "设置失败", "设置失败");
    }


    /**
     * 批量更新员工黑白名单
     * @return
     */
    @RequestMapping("/batchUpdateWhiteList")
    public ResponseBean batchUpdateWhiteList(String wy, String qy, String zy, String whiteList, String qrCode, Integer expDay, HttpServletRequest request) {

        String queryStr = null;
            queryStr = "gs";
        List<String> zyNameList = new ArrayList<>();
        if (StringUtil.isNotNull(queryStr)) {
            List<Dictionary> zyList = new ArrayList<>();
            if ("gs".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyGs();
            } else if ("jt".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyJt();
            }
            if (ValidateHelper.isNotEmptyCollection(zyList)) {
                for (Dictionary dictionary : zyList) {
                    if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                        zyNameList.add(dictionary.getName());
                    }
                }
            }
        }
        if (ValidateHelper.isNotEmptyString(wy)) { //物业不为空
            if (ValidateHelper.isNotEmptyString(qy)) { //企业不为空
                List<Staff> staffList = staffService.getStaffByQyId(qy);
                if (ValidateHelper.isEmptyCollection(staffList)) {
                    return new ResponseBean(500, "该企业下没有员工", "该企业下没有员工");
                }
                if (ValidateHelper.isNotEmptyString(zy)) {  //职业不为空
                    for (Staff staff : staffList) {
                        if (!zy.equals(staff.getZhiye())) {
                            continue;
                        }
                        if (whiteList.equals("1")) {
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("id", staff.getId());
                            updateWrapper.set("qrcode", "red");
                            updateWrapper.set("qrCodeExpDay", null);
                            updateWrapper.set("white_list", Integer.valueOf(whiteList));
                            staffService.update(updateWrapper);
                        } else {
                            staff.setWhiteList(Integer.valueOf(whiteList));
                            staff.setQrcode(qrCode);
                            staff.setQrCodeExpDay(expDay);
                            staff.setWhite_time(new Date());
                            staffService.updateById(staff);
                        }
                    }
                } else {  //物业不为空，企业不为空，职业为空
                    for (Staff staff : staffList) {
                        if (ValidateHelper.isNotEmptyCollection(zyNameList)) {
                            if (!zyNameList.contains(staff.getZhiye())) {
                                continue;
                            }
                        }
                        if (whiteList.equals("1")) {
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("id", staff.getId());
                            updateWrapper.set("qrcode", "red");
                            updateWrapper.set("qrCodeExpDay", null);
                            updateWrapper.set("white_list", Integer.valueOf(whiteList));
                            staffService.update(updateWrapper);
                        } else {
                            staff.setWhiteList(Integer.valueOf(whiteList));
                            staff.setQrcode(qrCode);
                            staff.setQrCodeExpDay(expDay);
                            staff.setWhite_time(new Date());
                            staffService.updateById(staff);
                        }
                    }
                }
            } else { // 物业不为空，企业为空
                if (ValidateHelper.isNotEmptyString(zy)) { // 物业不为空，企业为空，职业不为空
                    List<Qiye> qiyeList = qiyeService.selectQiyes(wy);
                    if (ValidateHelper.isEmptyCollection(qiyeList)) {
                        return new ResponseBean(500, "该物业下没有企业", "该物业下没有企业");
                    }
                    for (Qiye qiye : qiyeList) {
                        List<Staff> staffList = staffService.getStaffByQyId(qiye.getId());
                        if (ValidateHelper.isNotEmptyCollection(staffList)) {
                            for (Staff staff : staffList) {
                                if (!zy.equals(staff.getZhiye())) {
                                    continue;
                                }
                                if (whiteList.equals("1")) {
                                    UpdateWrapper updateWrapper = new UpdateWrapper();
                                    updateWrapper.eq("id", staff.getId());
                                    updateWrapper.set("qrcode", "red");
                                    updateWrapper.set("qrCodeExpDay", null);
                                    updateWrapper.set("white_list", Integer.valueOf(whiteList));
                                    staffService.update(updateWrapper);
                                } else {
                                    staff.setWhiteList(Integer.valueOf(whiteList));
                                    staff.setQrcode(qrCode);
                                    staff.setQrCodeExpDay(expDay);
                                    staff.setWhite_time(new Date());
                                    staffService.updateById(staff);
                                }
                            }
                        }
                    }
                } else { // 物业不为空，企业为空，职业为空
                    List<Qiye> qiyeList = qiyeService.selectQiyes(wy);
                    if (ValidateHelper.isEmptyCollection(qiyeList)) {
                        return new ResponseBean(500, "该物业下没有企业", "该物业下没有企业");
                    }
                    for (Qiye qiye : qiyeList) {
                        List<Staff> staffList = staffService.getStaffByQyId(qiye.getId());
                        if (ValidateHelper.isNotEmptyCollection(staffList)) {
                            for (Staff staff : staffList) {
                                if (ValidateHelper.isNotEmptyCollection(zyNameList)) {
                                    if (!zyNameList.contains(staff.getZhiye())) {
                                        continue;
                                    }
                                }
                                if (whiteList.equals("1")) {
                                    UpdateWrapper updateWrapper = new UpdateWrapper();
                                    updateWrapper.eq("id", staff.getId());
                                    updateWrapper.set("qrcode", "red");
                                    updateWrapper.set("qrCodeExpDay", null);
                                    updateWrapper.set("white_list", Integer.valueOf(whiteList));
                                    staffService.update(updateWrapper);
                                } else {
                                    staff.setWhiteList(Integer.valueOf(whiteList));
                                    staff.setQrcode(qrCode);
                                    staff.setQrCodeExpDay(expDay);
                                    staff.setWhite_time(new Date());
                                    staffService.updateById(staff);
                                }
                            }
                        }
                    }
                }
            }
        } else if (ValidateHelper.isNotEmptyString(qy)) {  //物业为空，企业不为空
            List<Staff> staffList = staffService.getStaffByQyId(qy);
            if (ValidateHelper.isEmptyCollection(staffList)) {
                return new ResponseBean(500, "该企业下没有员工", "该企业下没有员工");
            }
            if (ValidateHelper.isNotEmptyString(zy)) {  //职业不为空
                for (Staff staff : staffList) {
                    if (!zy.equals(staff.getZhiye())) {
                        continue;
                    }
                    if (whiteList.equals("1")) {
                        UpdateWrapper updateWrapper = new UpdateWrapper();
                        updateWrapper.eq("id", staff.getId());
                        updateWrapper.set("qrcode", "red");
                        updateWrapper.set("qrCodeExpDay", null);
                        updateWrapper.set("white_list", Integer.valueOf(whiteList));
                        staffService.update(updateWrapper);
                    } else {
                        staff.setWhiteList(Integer.valueOf(whiteList));
                        staff.setQrcode(qrCode);
                        staff.setQrCodeExpDay(expDay);
                        staff.setWhite_time(new Date());
                        staffService.updateById(staff);
                    }
                }
            } else {  //职业为空
                for (Staff staff : staffList) {
                    if (ValidateHelper.isNotEmptyCollection(zyNameList)) {
                        if (!zyNameList.contains(staff.getZhiye())) {
                            continue;
                        }
                    }
                    if (whiteList.equals("1")) {
                        UpdateWrapper updateWrapper = new UpdateWrapper();
                        updateWrapper.eq("id", staff.getId());
                        updateWrapper.set("qrcode", "red");
                        updateWrapper.set("qrCodeExpDay", null);
                        updateWrapper.set("white_list", Integer.valueOf(whiteList));
                        staffService.update(updateWrapper);
                    } else {
                        staff.setWhiteList(Integer.valueOf(whiteList));
                        staff.setQrcode(qrCode);
                        staff.setQrCodeExpDay(expDay);
                        staff.setWhite_time(new Date());
                        staffService.updateById(staff);
                    }
                }
            }
        } else if (ValidateHelper.isNotEmptyString(zy)) { //物业为空，企业为空 ，职业不为空
            List<Staff> staffList = staffService.getStaffByZhiye(zy);
            if (ValidateHelper.isEmptyCollection(staffList)) {
                return new ResponseBean(500, "该职业下没有员工", "该职业下没有员工");
            }
            for (Staff staff : staffList) {
                if (whiteList.equals("1")) {
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("id", staff.getId());
                    updateWrapper.set("qrcode", "red");
                    updateWrapper.set("qrCodeExpDay", null);
                    updateWrapper.set("white_list", Integer.valueOf(whiteList));
                    staffService.update(updateWrapper);
                } else {
                    staff.setWhiteList(Integer.valueOf(whiteList));
                    staff.setQrcode(qrCode);
                    staff.setQrCodeExpDay(expDay);
                    staff.setWhite_time(new Date());
                    staffService.updateById(staff);
                }
            }
        }

        return new ResponseBean(200, "批量设置成功", "批量设置成功");
    }

    /**
     * 批量导入黑白名单
     *
     * @param file
     * @return
     */
    @RequestMapping("/batchUploadWhiteList")
    public ResponseBean batchUploadWhiteList(@RequestParam MultipartFile file, HttpServletRequest request) {
        Integer whiteList = Integer.valueOf(request.getParameter("whiteList"));

        String fileName = file.getOriginalFilename();
        List<String> bhList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        boolean flag = com.excel.ExcelUtil.importExcelByHsJc(fileName, file, bhList);
        int i = 0;

        if (flag && bhList.size() > 0) {
            for (String bh : bhList) {
                String error = "";
                Staff staff = staffService.getStaffByBh(bh);
                if (null == staff) {
                    error = "<br>编号：<span style='color:red;'>" + bh + "不存在</span>";
                    errorList.add(error);
                    continue;
                }
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", staff.getId());
                updateWrapper.set("white_list", whiteList);
                if (whiteList == 0) {
                    updateWrapper.set("qrcode", request.getParameter("qrCode"));
                    updateWrapper.set("qrCodeExpDay", Integer.valueOf(request.getParameter("expDays")));
                    updateWrapper.set("white_time", new Date());
                } else {
                    updateWrapper.set("qrcode", "red");
                    updateWrapper.set("qrCodeExpDay", null);
                }

                if (staffService.update(updateWrapper)) {
                    i++;
                }
            }
        }
        int result = bhList.size() - i;
        if (result < 0) {
            result = 0;
        }

        if (ValidateHelper.isNotEmptyCollection(errorList)) {
            return new ResponseBean(500, 1, "总记录数：" + bhList.size() + ",成功数：" + i + ",失败数：" + "<span style='color:red;'>" + result + "</span>", errorList);
        }

        return new ResponseBean(200, 1, "总记录数：" + bhList.size() + ",成功数：" + i + ",失败数：" + result);
    }

    /**
     * 根据员工编号获取员工疫情相关信息
     *
     * @param bh
     * @return
     */
    @RequestMapping("/getStaffYqByBh")
    public ResponseBean getStaffYqByBh(String bh) {
        if (ValidateHelper.isEmptyString(bh)) {
            return new ResponseBean(500, "编号不能为空", "编号不能为空");
        }
        Staff staff = staffService.getStaffByBh(bh);
        if (null == staff) {
            return new ResponseBean(500, "员工不存在", "员工不存在");
        }
        Map resultMap = new HashMap();
        resultMap.put("staffId", staff.getId());
        resultMap.put("staffBh", staff.getBh());
        resultMap.put("staffName", staff.getName());
        resultMap.put("picture", staff.getPicture());
        if (staff.getWhiteList() == null) {
            resultMap.put("whiteList", "");
        } else {
            if (staff.getWhiteList() == 0) {
                resultMap.put("whiteList", "白名单");
            } else {
                resultMap.put("whiteList", "黑名单");
            }
        }

        if (staff.getWhite_time() == null) {
            resultMap.put("whiteTime", "");
        } else {
            resultMap.put("whiteTime", staff.getWhite_time());
        }

        if (staff.getQrCodeExpDay() == null) {
            resultMap.put("whiteExpDay", "");
        } else {
            resultMap.put("whiteExpDay", staff.getQrCodeExpDay());
        }

        Map<String, String> map = staffService.getQrCode(staff.getId());
        for (String key : map.keySet()) {
            String value = map.get(key);
            resultMap.put("qrCode", key);
            resultMap.put("remark", value);
        }

        return new ResponseBean(200, "成功", resultMap);
    }


    /**
     * 根据企业ID获取员工数量
     *
     * @param qyId
     * @return
     */
    @RequestMapping("/getStaffCountByQyId")
    public ResponseBean getStaffCountByQyId(String qyId) {
        if (ValidateHelper.isEmptyString(qyId)) {
            return ResponseBean.error("企业ID为空");
        }
        Qiye qiye = qiyeService.getById(qyId);
        if (null == qiye) {
            return ResponseBean.error("企业不存在");
        }

        long staffCount = staffService.getStaffCountByQyId(qyId);
        return new ResponseBean(200, "成功", staffCount);
    }

    /**
     * 批量修改员工企业
     *
     * @param file
     * @return
     */
    @PostMapping(value = "batchUpdateStaffQy")
    public ResponseBean batchUpdateStaffQy(@RequestParam MultipartFile file) {
        Map<String, String> resultMap = ExcelUtil.importExcelByUpdateStaffQy(file);
        if (resultMap.containsKey("error")) {
            return new ResponseBean(500, "失败", resultMap.get("error"));
        }
        if (resultMap.containsKey("success")) {
            return ResponseBean.ok("导入成功");
        }
        return new ResponseBean(500, "失败", "导入失败");
    }

    /**
     * 设置违规人员
     *
     * @param id
     * @param remark
     * @return
     */
//    @RequestMapping("/setStaffWeigui")
//    public ResponseBean setStaffWeigui(String id, String remark) {
//        Staff staff = staffService.selectID(id);
//        StaffWeigui staffWeigui = new StaffWeigui();
//        BeanUtils.copyProperties(staff, staffWeigui);
//        staffWeigui.setCreatetime(new Date());
//        staffWeigui.setWgRemark(remark);
//        staffWeigui.setOutStatus(0);
//        StaffWeigui saveStaffWg = staffWeiguiService.getById(id);
//        if (saveStaffWg != null) {
//            return ResponseBean.error("设置失败，违规员工已存在");
//        }
//        if (staffWeiguiService.save(staffWeigui)) {
//            if (staffService.removeById(id)) {
//                return ResponseBean.ok("设置成功");
//            }
//        }
//        return ResponseBean.error("删除失败");
//    }

}
